package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strconv"
	"strings"
	"studios/models"
	"time"
)

type StudiosController struct {
	beego.Controller
}
type JsonMsg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *StudiosController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price", 64)
	img := c.GetString("img")
	intro := c.GetString("intro")
	star := c.GetString("star")
	studios := models.Studios{
		Name:  name,
		Price: price,
		Img:   img,
		Intro: intro,
		Star:  star,
	}
	err := models.DB.Create(&studios).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *StudiosController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()

	if header.Size > 5*1024*1024 {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "文件不能超过5MB",
			Data: nil,
		}
		c.ServeJSON()
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	suffixMax := map[string]bool{
		".jpg": true,
		".png": true,
	}
	if !suffixMax[suffix] {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "文件只能是jpg,png格式",
			Data: nil,
		}
		c.ServeJSON()
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		ImgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "文件上传成功",
			Data: ImgSrc,
		}
		c.ServeJSON()
	}
}
func (c *StudiosController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 10)
	name := c.GetString("name")
	var total int64
	query := models.DB.Model(&models.Studios{})
	JsonData := make(map[string]interface{})
	if name != "" {
		query = query.Where("name like ? ", "%"+name+"%")
	}
	key := "studios" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	if err != nil {
		err = query.Count(&total).Error
		if err != nil {
			c.Data["json"] = JsonMsg{
				Code: 500,
				Msg:  "总数查询失败",
				Data: nil,
			}
			c.ServeJSON()
		}
		var studios []models.Studios
		err = query.Order("created_at desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&studios).Error
		if err != nil {
			c.Data["json"] = JsonMsg{
				Code: 500,
				Msg:  "分页失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {

			JsonData["studios"] = studios
			JsonData["total"] = total
			JsonByte, _ := json.Marshal(&JsonData)
			models.Rdb.Set(key, string(JsonByte), time.Second*10)
			c.Data["json"] = JsonMsg{
				Code: 200,
				Msg:  "分页成功",
				Data: JsonData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &JsonData)
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "分页成功-redis",
			Data: JsonData,
		}
		c.ServeJSON()
	}

}
func (c *StudiosController) Show() {
	id, _ := c.GetInt("id")
	var studios models.Studios
	Rank := "rank"
	models.Rdb.ZIncrBy(Rank, 1, strconv.Itoa(id))
	key := "key" + strconv.Itoa(id)
	val, err := models.Rdb.Get(key).Result()
	if err != nil {
		err = models.DB.Model(&models.Studios{}).Where("id = ?", id).First(&studios).Error
		if err != nil {
			c.Data["json"] = JsonMsg{
				Code: 500,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {
			JsonByte, _ := json.Marshal(&studios)
			models.Rdb.Set(key, string(JsonByte), time.Second*10)
			c.Data["json"] = JsonMsg{
				Code: 200,
				Msg:  "展示成功",
				Data: studios,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &studios)
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: studios,
		}
		c.ServeJSON()
	}

}
func (c *StudiosController) Rank() {
	key := "rank"
	result, err := models.Rdb.ZRevRange(key, 1, 9).Result()
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "排行榜失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	var studios []models.Studios
	for _, i := range result {
		var studio models.Studios
		err := models.DB.Model(&models.Studios{}).Where("id = ?", i).First(&studio).Error
		if err != nil {
			break
		}
		studios = append(studios, studio)
	}
	c.Data["json"] = JsonMsg{
		Code: 200,
		Msg:  "排行榜成功",
		Data: studios,
	}
	c.ServeJSON()
}
